/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent } from "react";
import { connect } from "dva";
import { Card, Form, Row, Col, Select, Input, DatePicker, Button } from "antd";
import { debounce } from "lodash";
import StandardTable from "@/components/StandardTable";
import DownloadBar from "@/components/DownloadBar";
import moment from "moment";
import PageHeaderLayout from "@/layouts/PageHeaderLayout";
import { timeDistance, dateCalendar } from "@/utils/utils";
import styles from "./style.less";


const Option = Select.Option;
const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const dataFormat = "YYYY-MM-DD";

const formItemLayout = {
  labelCol: {
    xs: { span: 0 },
    sm: { span: 8 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
};

@connect(({ history, loading }) => ({
  history,
  submitLoading: loading.effects["history/getHistoryList"]
}))
@Form.create()
export default class History extends PureComponent {
  componentDidMount() {
    this.handleSearch();
  }

  handleSearch = debounce((e, page = 1, size = 20) => {
    e && e.preventDefault();
    const {
      form: { validateFields },
      dispatch
    } = this.props;
    validateFields((err, values) => {
      if (err) {
        return;
      }
      dispatch({
        type: "history/getHistoryList",
        payload: {
          courier_keyword: values.courier_keyword,
          user_keyword: values.user_keyword,
          order_id: values.order_id,
          status: values.status,
          start_time: moment(values.date[0]).format(dataFormat),
          end_time: moment(values.date[1]).format(dataFormat),
          page,
          size
        }
      });
    });
  }, 500, {
    leading: true,
    trailing: false
  });

  handleStandardTableChange = e => {
    this.handleSearch("", e.current, e.pageSize);
  };

  downloadData = () => {
    const {
      form: { validateFields }
    } = this.props;
    let query = {};
    validateFields((err, values) => {
      query = {
        data: JSON.stringify({
          data: {
            courier_keyword: values.courier_keyword,
            user_keyword: values.user_keyword,
            order_id: values.order_id,
            status: values.status,
            start_time: moment(values.date[0]).format(dataFormat),
            end_time: moment(values.date[1]).format(dataFormat),
            is_excel: 1
          },
          run: "/DeliveryOrderCount/historyDetails",
          time: new Date().getTime()
        })
      };

    });
    return {
      ...query
    };
  };

  render() {
    const {
      form: { getFieldDecorator },
      submitLoading,
      history: { historyList }
    } = this.props;
    const columns = [
      {
        title: "订单编号",
        dataIndex: "id",
        render: text => {
          return <a href="javascript:">{text}</a>;
        }
      },
      {
        title: "订单详情",
        render: (text, record) => {
          return (
            <div>
              {
                record.package_way == "send" ? <div>
                  <p>
                    取件地址：
                    {record.shipper_province}{record.shipper_city}{record.shipper_district}{record.shipper_address}
                  </p>
                  <p>
                    送达地址：
                    {record.shipping_province}{record.shipping_city}{record.shipping_district}{record.shipping_address}
                  </p>
                </div> : <div>
                  <p>
                    取件地址：
                    {record.shipping_province}{record.shipping_city}{record.shipping_district}{record.shipping_address}
                  </p>
                  <p>
                    送达地址：
                    {record.shipping_province}{record.shipping_city}{record.shipping_district}{record.shipping_address}
                  </p>
                </div>
              }

              <p>
                距离：
                {
                  Math.round(record.path_distance/1000*100)/100
                }
                公里 &nbsp;&nbsp;重量：
                {record.package_weight}
                &nbsp;&nbsp;物品类型：
                {record.package_info || "暂无"}
              </p>
              <div>
                <span className={styles.time_width}>
                  下单时间：{record.published_at && record.published_at !="0000-00-00 00:00:00" ?(
                  dateCalendar(record.published_at)
                ) : "-"}
                </span>
                &nbsp;&nbsp;
                <span className={styles.time_width}>
                  接单时间：{record.accepted_at && record.accepted_at !="0000-00-00 00:00:00" ? (
                  dateCalendar(record.accepted_at)
                ) : "-"}
                </span>
              </div>
              <div>
                {" "}
                <span className={styles.time_width}>
                  取件时间：{record.acquired_at && record.acquired_at !="0000-00-00 00:00:00" ? (
                  dateCalendar(record.acquired_at)
                ) : "-"}
                </span>
                &nbsp;&nbsp;
                <span className={styles.time_width}>
                  送达时间：{record.arrived_at && record.arrived_at !="0000-00-00 00:00:00" ? (
                  dateCalendar(record.arrived_at)
                ) : "-"}
                </span>
              </div>
              <div>
                <span className={styles.time_width}>
                  完成时间：{record.arrived_at && record.arrived_at !="0000-00-00 00:00:00" ? (
                  dateCalendar(record.arrived_at)
                ) : "-"}
                </span>
              </div>
            </div>
          );
        }
      },
      {
        title: "下单客户",
        render: (text, record) => {
          return (
            <div>
              <p>{record.shipping_name}</p>
              <p>{record.shipping_mobile || record.shipping_tel}</p>
            </div>
          );
        }
      },
      {
        title: "配送员",
        render: (text, record) => {
          return (
            <div>
              <p>{record.collect_courier_name}</p>
              <p>{record.collect_courier_mobile}</p>
            </div>
          );
        }
      },
      {
        title: "配送时长",
        dataIndex: "time",
        render: (text, record) => {
          if (record.status == "canceled") {
            return "--";
          } else {
            return timeDistance(record.arrived_at, record.accepted_at);
          }
        }
      },
      {
        title: "配送费(元)",
        dataIndex: "receipts"
      },
      {
        title: "订单状态",
        dataIndex: "status",
        render: text => {
          return <span>{text == "canceled" ? "已取消" : "已完成"}</span>;
        }
      }
    ];
    return (
      <PageHeaderLayout title="历史订单">
        <div className={styles.main}>
          <Card bordered={false} bodyStyle={{ padding: "0 0 24px" }}>
            <Form onSubmit={this.handleSearch} className={styles["search-form"]}>
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={8} sm={24}>
                  <FormItem {...formItemLayout} label="订单完成日期">
                    {getFieldDecorator("date", {
                      initialValue: [
                        moment(new Date()).add(-1, "month"),
                        moment(new Date()).add("-1", "day")
                      ]
                    })(
                      <RangePicker
                        style={{ width: "100%" }}
                        placeholder={["开始日期", "结束日期"]}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col md={6} sm={24}>
                  <FormItem label="下单客户" {...formItemLayout}>
                    {getFieldDecorator("user_keyword")(
                      <Input placeholder="请输入客户姓名或手机号" />
                    )}
                  </FormItem>
                </Col>
                <Col md={6} sm={24}>
                  <FormItem label="配送员" {...formItemLayout}>
                    {getFieldDecorator("courier_keyword")(
                      <Input placeholder="请输入配送员姓名或手机号" />
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={8} sm={24}>
                  <FormItem label="订单编号" {...formItemLayout}>
                    {getFieldDecorator("order_id")(<Input placeholder="请输入订单编号" />)}
                  </FormItem>
                </Col>
                <Col md={6} sm={24}>
                  <FormItem {...formItemLayout} label="订单状态">
                    {getFieldDecorator("status", {
                      initialValue: "all"
                    })(
                      <Select showSearch allowClear placeholder="请选择订单状态">
                        <Option value="all">全部状态</Option>
                        <Option value="finished">已完成</Option>
                        <Option value="canceled">已取消</Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col md={6} sm={24}>
                  <FormItem {...formItemLayout} label=" " colon={false}>
                    <Button type="primary" icon='search' htmlType="submit" key="search" loading={submitLoading}>
                      查询
                    </Button>
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </Card>
          <div style={{ paddingBottom: "24px" }}>
            <DownloadBar
              className='mr-10'
              href="/Api/Handle/run"
              query={this.downloadData}
            >
              <Button type="primary" icon="download">
                导出
              </Button>
            </DownloadBar>
          </div>
          <StandardTable
            rowKey="id"
            loading={submitLoading}
            data={historyList}
            columns={columns}
            onChange={this.handleStandardTableChange}
          />
        </div>
      </PageHeaderLayout>
    );
  }
}
